package cn.yoline.xylink.utils;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

import java.util.HashMap;

import cn.yoline.xylink.R;

/**
 * @file MediaSoundUtil
 * Created by linaisheng on 2020/5/21.
 * <p>Copyright 2020 JxGIS.</p>
 * Description：
 */
public class MeetingSoundUtil {
    private static final int KEY_INCOMING_CALL_SOUND = 1;

    private static final String TAG = MeetingSoundUtil.class.getSimpleName();

    private static volatile MeetingSoundUtil sSoundPoolUtil;
    private final Context mContext;
    private final SoundPool mSoundPool;
    private final HashMap<Integer, Integer> mSoundMap;
    private int mCurrentId;
    //声音资源加载完成的标识位
    private boolean mHasLoaded;

    private MeetingSoundUtil(Context context) {
        mContext = context.getApplicationContext();
        mSoundPool = new SoundPool(2, AudioManager.STREAM_SYSTEM,0);
        mSoundMap = new HashMap<>();

        mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                mHasLoaded = true;
            }
        });

        mSoundMap.put(KEY_INCOMING_CALL_SOUND, mSoundPool.load(mContext, R.raw.incoming_call,1));
    }

    public static MeetingSoundUtil getInstance(Context context) {
        if (sSoundPoolUtil == null) {
            synchronized (MeetingSoundUtil.class) {
                if (sSoundPoolUtil == null) {
                    sSoundPoolUtil = new MeetingSoundUtil(context);
                }
            }
        }
        return sSoundPoolUtil;
    }

    public void playIncomingCallSound() {
        stopPlay();
        if (!mHasLoaded) {
            mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                @Override
                public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                    if (sampleId == mSoundMap.get(KEY_INCOMING_CALL_SOUND)) {
                        playSoundId(mSoundMap.get(KEY_INCOMING_CALL_SOUND), true);
                    }
                    mHasLoaded = true;
                }
            });
        } else {
            playSoundId(mSoundMap.get(KEY_INCOMING_CALL_SOUND), true);
        }
    }

    public void stopPlay() {
        if (mCurrentId != 0) {
            mSoundPool.stop(mCurrentId);
        }
    }

    private int playSoundId(int sampleId,boolean isLoop) {
        mCurrentId = mSoundPool.play(sampleId, 1f, 1f, 1, isLoop ? -1 : 0, 1);
        return mCurrentId;
    }
}